var app = getApp()
import Poster from '../../poster-plugin/poster/poster';
const posterConfig = require('../../config/poster.js');
var util = require('../../utils/util.js')
var base64 = require('../../utils/base64.js')
var event = require('../../utils/event.js');
import {
  SoundPlayer
} from "../../utils/soundPlayer.js";
const date_util = require('../../utils/date_util.js')
var api = require('../../config/api.js')
var player = new SoundPlayer();
const navigationBarHeight = (getApp().statusBarHeight + 44) + 'px'
const myaudio = wx.createInnerAudioContext();
const posterFeelingConfig = posterConfig.getPosterFeelingCinfig();
import ColorThief from '../../utils_color/color-thief.js'
import {
  rgbToHex,
  uuid,
  colorsEqual,
  saveBlendent,
  getPicColor
} from '../../utils_color/util.js'
const picIcon = [
  'https://qn.simullink.com/FocVsylregOdmd8KFxagoOfkGa4y', 'https://qn.simullink.com/Fj1Bo9ne1iL9_c9FH86dUXqJMpe5',
  'https://qn.simullink.com/Fr1L8X6UPxcBOydhVSHD3sEniuWC', 'https://smtestopen.blcclb.com/FsDKjZP32Xifzg06K1QAn0yHToDY'
];

Page({
  data: {
    navigationBarHeight,
    statusBarHeight: app.statusBarHeight + 'px',
    id: 0,
    isIphoneX: app.globalData.isIphoneX ? true : false,
    myfollowacts: [],
    uuid: '',
    showPage: false,
    activityInfo: {},
    phValue: '表达感受...',
    comment_content: '',
    commentflag: false,
    simulflag: false,
    userInfo: app.globalData.userInfo,
    auth: app.globalData.auth,
    systemInfo: {},
    hasUserInfo: app.globalData.hasUserInfo,
    hasPhone: app.globalData.hasPhone,
    // 父评论相关参数
    fatherComments: {},
    fatherCommentsisEmpty:false,
    activityisEmpty:false,
    ds: '',
    // 子评论相关参数
    sonComments: [],
    sonPage: 1,
    sonSize: 20,
    comment: [],
    simul: [],
    hiddenDelete: true,
    hiddenAll: true,
    hiddenShare: true,
    hiddenNavigation: true,
    hiddenWxShare: true,
    sharepicurl: '',
    shareImg: '',
    shareindex: -1,
    currentTab: 0,
    isPlay: false,
    //轮播相关
    faAutoplay: false,
    faIndicatorDots: false,
    //分享相关
    commId: 0, //分享过来的评论id
    source: 'app',
    scene: '',
    //标记扫码进入
    flag: 0,
    //选项卡效果
    curIndex: 0, //当前显示的view下标
    marginWidth:0
  },


  onLoad: function(options) {
    var that = this;
    that.colorThief = new ColorThief('canvasidii');

    var uuid = ''; //活动id
    var commId = 0; //评论id 没有写0   
    var source = "app";

    const scene = decodeURIComponent(options.scene)
    if ((typeof(scene) != undefined) && scene != 'undefined') { //扫码进入    
      that.setData({
        scene: scene,
        source: 'app'
      })
      that.getSharePara(scene);
    } else {
      that.setData({
        flag: 1
      })
      uuid = options.uuid;
      commId = options.commId;
      source = options.source
    }
    //  'b24f663277744de4bae9c519755154fc'
    // 3930 tupian
    // 3279 shipin 
    // 2631 wenzi
    // 493 yuyin

    wx.showShareMenu({
      withShareTicket: true
    });

    wx.hideShareMenu();

    that.setData({
      commId: commId,
      uuid: uuid,
      source: source,
      userInfo: app.globalData.userInfo,
      hasUserInfo: app.globalData.hasUserInfo,
      auth: app.globalData.auth,
      hasPhone: app.globalData.hasPhone,
    });

    wx.getSystemInfo({
      success: function(res) {
        let w = res.windowWidth,
          h = res.windowHeight;
        that.setData({
          winWidth: w,
          winHeight: h,
          systemInfo: res,
          marginWidth: (res.windowWidth - 166) / 2
        })
      },
    })
  },
  //解析扫码分享的参数
  getSharePara: function(id) {
    var that = this
    util.pututrequest(api.crackScene + '?scene=' + id, 'GET').then((res) => {
      if (res && res.code == 200) {
        res = res.data;
        that.setData({
          source: 'app',
          commId: res.id,
          userInfo: app.globalData.userInfo,
          auth: app.globalData.auth,
          hasPhone: app.globalData.hasPhone,
        });

        that.getFatherComments()

      }
    })
  },

  onMyevent: function(e) {
    var that = this
    that.setData({
      userInfo: e.detail.paramBtoA.userInfo,
      auth: e.detail.paramBtoA.auth,
      hasPhone: e.detail.paramBtoA.hasPhone,
    })
  },
  launchAppError: function(e) {
    wx.getSystemInfo({
      success: function(res) {
        let type = res.system
        if (type.indexOf("Android") != -1) {
          wx.showModal({
            title: '跳转至同感App',
            showCancel: false,
            content: '亲爱的主人，很遗憾,同感app暂时未支持您的设备类型,您还是在小程序里尽情玩耍吧！'
          })
        }
        if (type.indexOf("iOS") != -1) {
          wx.showModal({
            title: '跳转至同感App',
            showCancel: false,
            content: '亲爱的主人，请到AppStore里下载同感App查看更多同感动态！'
          })
        }
      }
    })
  },
  onReady: function() {
    var that = this
  },
  onShow: function() {
    if (this.data.flag > 0) {
      // this.getDetailInfo(this.data.uuid)
      this.getFatherComments()
    }
  },
  onHide: function() {},
  onUnload: function() {},
  //一、 详情页功能
  getDetailInfo: function(uuid) {
    var that = this;
    var followers = [];
    var i = 0;
    util.pututrequest(api.activityInfoMeta + '?activityId=' + uuid, 'GET').then((res) => {
      if (res && res.code == 200) {
        let venue = res.data.venue
        let activity = res.data.activity

        let title_title = util.mixTextOverflow(activity.name, 16)
        activity.followers = res.data.followUsers;
        activity.title_title = title_title;
        activity.acti_photo = activity.coverUrl +'?imageMogr2/thumbnail/370x/format/jpg/size-limit/80k!'

        that.setData({
          activityInfo: activity,
          activityisEmpty:true
        })
      }
    });
  },

  // 返回上一页
  backhomepage: function() {
    var that = this;
    wx.switchTab({
      url: '/pages/index/index'
    });
    player.stop()
    let fatherComments = that.data.fatherComments
    fatherComments.bl = false;
    that.setData({
      fatherComments: fatherComments
    })
  },
  gotoVideo: function(e) {
    var that = this;
    var item = that.data.fatherComments
    var dir = item.direction
    item.source = 'detail'
    let itemStr = JSON.stringify(item)
    // base64 encode
    let item64 = base64.encode(itemStr)
    // url encode
    let itemEncode = encodeURIComponent(item64)
    wx.navigateTo({
      url: '/pages/video/video?dataObj=' + itemEncode + '&uuid=' + this.data.activityInfo.uuid + '&title=' + this.data.activityInfo.title + '&pic=' + this.data.activityInfo.image_path + '&source=detail' + '&direction=' + dir,
      success: function() {},
      fail: function() {},
      complete: function() {}
    })
  },

  tongGan: function(e) {
    let index = e.currentTarget.dataset.index
    let count = this.data.fatherComments.simul_count
    let photos = this.data.fatherComments.simul_photos

    var that = this
    that.auth = that.selectComponent("#auth");
    if (that.data.auth && that.data.hasPhone) {
      util.pututrequest(api.tongGan, 'POST', {
        activityId: that.data.uuid,
        feelingId: that.data.commId
      }).then(res => {
        if (res && res.code == 200) {
          var tt = 'fatherComments.currentUserCollected'
          var ff = 'fatherComments.simul_count'
          var simul = 'fatherComments.simul_photos'

          var info = that.data.userInfo
          info["photo"] = info.avatarUrl
          photos.push(info)
          if (photos.length > 3) {
            photos.shift()
          }

          this.setData({
            [tt]: true,
            [ff]: count + 1,
            [simul]: photos,
          })
          wx.showToast({
            title: '深有同感',
            icon: 'success',
            duration: 2000
          })
        }
      })
    } else {
      that.auth.showAuth();
    }
  },

  cancelTongGan: function (e) {
    var that = this
    let count = this.data.fatherComments.simul_count
    let photos = this.data.fatherComments.simul_photos 
    that.auth = that.selectComponent("#auth");
    if (that.data.auth && that.data.hasPhone) {
      util.pututrequest(api.tongGan + '?feelingId=' + that.data.commId, 'DELETE').then(res => {
        if (res && res.code == 200) {
          var tt = 'fatherComments.currentUserCollected'
          var ff = 'fatherComments.simul_count'
          var simul = 'fatherComments.simul_photos'
          var delId = 0
          for (var i = 0; i < photos.length; i++) {
            let oneFollow = photos[i]
            if (oneFollow.id == that.data.userInfo.id) {
              delId = i
              break
            }
          }
          photos.splice(delId, 1)

          this.setData({
            [tt]: false,
            [ff]: count - 1,
            [simul]: photos,
            hiddenDelete:true,
            hiddenAll:true
          })
          wx.showToast({
            title: '取消同感',
            icon: 'success',
            duration: 2000
          })
        }
      })
    } else {
      that.auth.showAuth();
    }

  },


  feelingFirstLineLocation: function(type, avatarUrl, nickname, viplevel, emoji) {
    posterFeelingConfig[type + 'Config'].images = []
    posterFeelingConfig[type + 'Config'].texts = []
    let len = 15,
      textStart = 120,
      jiange = 15;
    let textWidth = util.getTextLength(nickname) * len;
    posterFeelingConfig[type + 'Config'].images.push({
      width: 80,
      height: 80,
      x: 20,
      y: 30,
      borderRadius: 80,
      url: avatarUrl,
    })
    posterFeelingConfig[type + 'Config'].texts.push({
      x: textStart,
      y: 70,
      baseLine: 'middle',
      text: nickname,
      width: textWidth,
      fontSize: 32,
      color: '#000000',
    })
    if (viplevel > 0) {
      let kolStart = textStart + textWidth + jiange;
      posterFeelingConfig[type + 'Config'].images.push({
        width: 24,
        height: 24,
        x: kolStart,
        y: 58,
        borderRadius: 24,
        url: '',
      })
    }
    if (emoji) {
      let gandaoStart = textStart + textWidth + jiange;
      if (viplevel > 0) {
        gandaoStart = gandaoStart + 24 + jiange;
      }
      posterFeelingConfig[type + 'Config'].texts.push({ //感到
        x: gandaoStart,
        y: 70,
        baseLine: 'middle',
        text: '感到',
        width: 40,
        fontSize: 32,
        color: '#FF0000',
      })
      posterFeelingConfig[type + 'Config'].texts.push({ //表情
        x: gandaoStart + 60 + jiange,
        y: 70,
        baseLine: 'middle',
        text: emoji,
        fontSize: 32,
        color: '#000000',
      })
    }
  },
  


  deleteComment: function (e) {
    var that = this    
    that.auth = that.selectComponent("#auth");
    if (that.data.auth && that.data.hasPhone) {
      that.setData({
        hiddenDelete: false,
        hiddenAll:false
      })
    } else {
      that.auth.showAuth();
    }
  },
  deleteFeeling: function () {
    var that = this
    let fa = that.data.fatherComments
    let feeling = fa
    wx.showModal({
      title: '删除感受',
      content: '您确定删除这条感受吗？',
      showCancel: true, //是否显示取消按钮
      cancelText: "取消", //默认是“取消”
      cancelColor: '#0000FF',
      confirmText: "确定",
      confirmColor: '#DC143C', //确定文字的颜色
      success: function (ress) {
        if (ress.cancel) {
          //点击取消,默认隐藏弹框
        } else {
          //点击确定
          util.pututrequest(api.uploadTonggan + '?feelingId=' + feeling.id + '&activityId=' + that.data.activityInfo.id, 'DELETE').then(res => {
            if (res && res.code == 200) {
              feeling={}
              that.setData({
                fatherComments: feeling,
                fatherCommentsisEmpty:false,
                hiddenDelete: true,
                hiddenAll:true
              })
            }
          })
          //点击确定
        }
      },
      fail: function (ress) { }, //接口调用失败的回调函数
      complete: function (ress) { }, //接口调用结束的回调函数（调用成功、失败都会执行）
    })
  },


  // 分享活动
  updateFeelingPosterConfig: function(bgColor, feeling, qrcode) { //picIcon数组  feeling一条感受对象  qrcode二维码图片url
    this.feelingFirstLineLocation(feeling.type, feeling.user.avatarUrl, feeling.user.nickname, feeling.user.vipLevel, feeling.emotion)

    if (feeling.type == 'VIDEO') {
      if (feeling.user.vipLevel > 0) {
        posterFeelingConfig.VIDEOConfig.images[1].url = picIcon[0]
      }
      posterFeelingConfig.VIDEOConfig.images.push({
        width: 630,
        height: 700,
        x: 20,
        y: 123,
        borderRadius: 40,
        url: feeling.thumbnail,
      })

      posterFeelingConfig.VIDEOConfig.texts.push({
        x: 20,
        y: 865,
        baseLine: 'left',
        text: feeling.content,
        width: 600,
        fontSize: 32,
        color: '#000000',
        zIndex: 100,
      })

      posterFeelingConfig.VIDEOConfig.images.push({ //play标记
        width: 50,
        height: 50,
        x: 320,
        y: 470,
        borderRadius: 50,
        url: picIcon[1],
      })

      posterFeelingConfig.VIDEOConfig.images.push({ //二维码
        width: 100,
        height: 100,
        x: 292,
        y: 940,
        borderRadius: 100,
        url: qrcode,
      })
    }


    if (feeling.type == 'IMAGE') {
      if (feeling.user.vipLevel > 0) {
        posterFeelingConfig.IMAGEConfig.images[1].url = picIcon[0]
      }
      posterFeelingConfig.IMAGEConfig.images.push({
        width: 630,
        height: 700,
        x: 20,
        y: 123,
        borderRadius: 40,
        url: feeling.images_new[0].url,
      })

      posterFeelingConfig.IMAGEConfig.texts.push({
        x: 20,
        y: 865,
        baseLine: 'left',
        text: feeling.content,
        width: 600,
        fontSize: 32,
        color: '#000000',
        zIndex: 100,
      })
      posterFeelingConfig.IMAGEConfig.images.push({
        width: 100,
        height: 100,
        x: 292,
        y: 940,
        borderRadius: 100,
        url: qrcode,
      })
    }


    if (feeling.type == 'AUDIO') {
      posterFeelingConfig.AUDIOConfig.blocks[0].backgroundColor = bgColor
      if (feeling.user.vipLevel > 0) {
        posterFeelingConfig.AUDIOConfig.images[1].url = picIcon[0]
      }
      posterFeelingConfig.AUDIOConfig.texts.push({
        x: 120,
        y: 480,
        baseLine: 'left',
        text: feeling.content,
        width: 400,
        fontSize: 32,
        color: '#fff',
        zIndex: 100,
      })

      posterFeelingConfig.AUDIOConfig.images.push({
        width: 450,
        height: 60,
        x: 110,
        y: 360,
        url: picIcon[1],
      })

      posterFeelingConfig.AUDIOConfig.images.push({
        width: 100,
        height: 100,
        x: 292,
        y: 860,
        borderRadius: 100,
        url: qrcode,
      })
    }

    if (feeling.type == 'TEXT') {
      posterFeelingConfig.TEXTConfig.blocks[0].backgroundColor = bgColor
      if (feeling.user.vipLevel > 0) {
        posterFeelingConfig.TEXTConfig.images[1].url = picIcon[0]
      }

      posterFeelingConfig.TEXTConfig.texts.push({
        x: 120,
        y: 485,
        baseLine: 'left',
        text: feeling.content,
        width: 400,
        fontSize: 32,
        color: '#fff',
        zIndex: 100,
      })

      posterFeelingConfig.TEXTConfig.images.push({
        width: 50,
        height: 50,
        x: 110,
        y: 390,
        borderRadius: 50,
        url: picIcon[2],
      })

      posterFeelingConfig.TEXTConfig.images.push({
        width: 100,
        height: 100,
        x: 292,
        y: 880,
        borderRadius: 100,
        url: qrcode,
      })

    }

  },

  sharePic: function() {
    var that = this
    that.auth = that.selectComponent("#auth");
    if (that.data.auth && that.data.hasPhone) {
      that.setData({
        hiddenAll: false,
        hiddenNavigation: false,
        sharepicurl: ''
      })
    } else {
      that.auth.showAuth()
    }
  },

  close_share: function(e) {
    this.setData({
      hiddenShare: true,
      hiddenNavigation: true,
      hiddenWXShare: true,
      hiddenAll: true
    })
    if (this.data.shareindex >= 0) {
      var act = this.data.fatherComments
      if (act.type == 'VIDEO') {
        this.setData({
          isPlay: true
        })
      }
      this.setData({
        sharepicurl: ''
      })
    }
  },

  generatePoster: function() {
    var that = this
    that.getSharePoster()
    that.setData({
      hiddenShare: false,
      hiddenNavigation: true,
      hiddenWXShare: true
    })
  },
  saveWX: function() {
    var that = this
    that.setData({
      hiddenShare: false,
      hiddenNavigation: true,
      hiddenWXShare: false
    })
  },

  generateWXPoster: function() {
    var that = this
    that.getSharePoster()
    that.setData({
      hiddenShare: true,
      hiddenNavigation: true,
      hiddenWXShare: false
    })
  },

  getSharePoster: function() {
    let that = this
    let type = 'FEELING'
    var activityOrFeeling = that.data.fatherComments
    wx.showLoading({
      title: '生成海报...',
      mask: true,
    })
    util.pututrequest(api.generateQrcode, 'POST', {
      id: activityOrFeeling.id,
      type: type
    }).then(res => {
      if (res && res.code == 200) {
        let qrcode = res.data.url
        if (qrcode) {
          if (type == 'FEELING') {
            if (activityOrFeeling.type == 'AUDIO' || activityOrFeeling.type == 'TEXT') {
              const imagePath = that.data.activityInfo.coverUrl
              getPicColor(imagePath, that.colorThief).then(res => {
                that.updateFeelingPosterConfig(res, activityOrFeeling, qrcode)
                this.setData({
                  posterSendConfig: posterFeelingConfig[activityOrFeeling.type + 'Config']
                }, () => {
                  Poster.create(true); // 入参：true为抹掉重新生成 
                });
              })

            } else {
              that.updateFeelingPosterConfig('', activityOrFeeling, qrcode)
              this.setData({
                posterSendConfig: posterFeelingConfig[activityOrFeeling.type + 'Config']
              }, () => {
                Poster.create(true); // 入参：true为抹掉重新生成 
              });
            }
          }

        } else {
          wx.showModal({
            title: '二维码获取失败',
            showCancel: false,
            content: '该活动海报的二维码获取失败,请重新生成！'
          })
        }

      }
    });
  },

  onPosterSuccess(e) {
    const {
      detail
    } = e;
    this.setData({
      hiddenShare: false,
      sharepicurl: detail
    })
    wx.hideLoading()
  },
  onPosterFail(err) {
    console.error(err);
  },

  cancleMask: function() {
    this.setData({
      commentflag: false,
      hiddenDelete: true,
      simulflag: false,
      showUpload: true,
      hiddenAll: true,
      hiddenShare: true,
      hiddenNavigation: true,
      hiddenWXShare: true
    })
  },

  saveNetPicToLocal: function() {
    let that = this
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    //图片保存到本地
    wx.saveImageToPhotosAlbum({
      filePath: that.data.sharepicurl,
      success: function(data) {
        wx.showModal({
          title: '保存成功',
          content: '活动海报保存到相册成功',
          confirmText: "我知道了",
          showCancel: false,
        })
      },
      fail: function(err) {
        if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
          wx.openSetting({
            success(settingdata) {
              if (settingdata.authSetting['scope.writePhotosAlbum']) {
                wx.showToast({
                  title: '授权成功，继续保存',
                  icon: 'success',
                  duration: 2000
                })
              } else {
                wx.showToast({
                  title: '未授权，无法保存',
                  icon: 'success',
                  duration: 2000
                })
              }
            }
          })
        }
      },
    })
    wx.hideLoading()
  },
  onShareAppMessage: function(ops) {
    var that = this
    var index = 0
    var img = ''
    if (ops.from === 'button') { //页面内转发按钮      
      img = this.data.sharepicurl
    }

    var act = that.data.fatherComments
    var shareText = ""
    if (act.content && act.content != '') {
      shareText = act.content
    } else {
      shareText = that.data.activityInfo.name
    }

    return {
      title: shareText,
      desc: shareText,
      path: '/pages/share/share?uuid=' + that.data.activityInfo.id + '&source=app&commId=' + act.id + '&type=1',
      imageUrl: img,
      success: function(res) { // 转发成功       
        var shareTickets = res.shareTickets;
        if (shareTickets.length == 0) {
          return false;
        }
        //可以获取群组信息
        if (this.data.systemInfo.platform == 'android' && (shareTickets.length > 0)) {
          wx.getShareInfo({
            shareTicket: shareTickets[0],
            success: function(res) {
              wx.showToast({
                title: "分享成功",
                duration: 2000
              });
            },
            fail: function() {
              wx.showToast({
                title: "分享失败",
                duration: 2000
              });
            }
          })
        }
        if (this.data.systemInfo.platform == 'ios' && (shareTickets.length > 0)) {
          wx.showToast({
            title: "分享成功",
            duration: 2000
          });
        }
      },
      fail: function(res) { // 转发失败        
        wx.showToast({
          title: "分享失败，请重新分享",
          duration: 2000
        });
      }
    }
  },

  // 1.获取活动的父评论
  showLoadTip: function() {
    wx.showLoading({
      title: '正在加载中...',
      mask: true
    })
  },
  folded_change: function(e) {
    var that = this
    let index = e.currentTarget.dataset.index
    let t = that.data.fatherComments.isFolded
    let tt = 'fatherComments.isFolded'
    that.setData({
      [tt]: !t
    })
  },
  getFatherComments: function() {
    var that = this;
    util.pututrequest(api.getCommentById + '?id=' + that.data.commId, 'GET').then((res) => {
      if (res && res.code == 200) {
        if (res.data) {
          var feeling = res.data.feeling

          that.getDetailInfo(feeling.activityId);

          var simulUsers = res.data.simulUsers
          var user = res.data.user

          // var orifatherCom = feeling

          feeling.nickname = util.mixTextOverflow(user.nickname, 14)
          feeling.isFolded = true
          feeling.photoPath = user.avatarUrl
          // 同感头像     
          feeling.simul_photos = simulUsers
          feeling.simul_count = res.data.simulCount
          feeling.comment_count = res.data.commentCount
          feeling.currentUserCollected = res.data.isSimul
          feeling.user = user

          if (feeling.type == "VIDEO") {
            let feelingMedia = feeling.media && feeling.media.length > 0 ? feeling.media[0] : {}
            feeling.thumbnail = ''
            if (feelingMedia && JSON.stringify(feelingMedia) != "{}") {
              feeling.thumbnail = feelingMedia.thumbnailUrl +'?imageView2/0/h/668/format/jpg'
            }
          }

          if (feeling.type == "AUDIO") {
            let feelingMedia = feeling.media && feeling.media.length > 0 ? feeling.media[0] : {}
            feeling.thumbnail = ''
            if (feelingMedia && JSON.stringify(feelingMedia) != "{}") {
              feeling.path = feelingMedia.url
            }
          }


          if (feeling.type == "IMAGE") { //2
            let feelingMedias = feeling.media && feeling.media.length > 0 ? feeling.media : []
            let picArray = []
            for (var j = 0; j < feelingMedias.length; j++) {
              var oneMedia = feelingMedias[j]
              var url = '',url_src='';
              url = oneMedia.thumbnailUrl +'?imageView2/0/h/668/format/jpg'
              url_src = oneMedia.thumbnailUrl 
              picArray.push({
                'direction': 'shu',
                'url': url,
                'url_src':url_src
              })
            }
            feeling.images_new = picArray
          } //2

          feeling.txtheight = 'txt_normal'
          feeling.bl = false
          that.setData({
            fatherComments: feeling,
            uuid: feeling.activityId,
            fatherCommentsisEmpty:true,
            showPage: true
          })

        } else {
          that.setData({
            showPage: true,
            fatherComments: {},
            fatherCommentsisEmpty:false
          })
        }

      }
    });
  },

  thumbnailLoad: function(e) {
    var that = this;
    var item = that.data.fatherComments
    let dir = ''
    let originalWidth = e.detail.width;
    let originalHeight = e.detail.height;
    if (originalWidth > originalHeight) {
      dir = 'heng'
    } else {
      dir = 'shu'
    }

    var valueset = 'fatherComments.direction';
    this.setData({
      [valueset]: dir
    })

  },
  imageLoad: function(e) { //获取图片的原始宽度和高度
    let sonindex = e.currentTarget.dataset.sonindex
    let originalWidth = e.detail.width;
    let originalHeight = e.detail.height;
    let dir = ''
    if (originalWidth > originalHeight) {
      dir = 'heng'
    } else {
      dir = 'shu'
    }
    var valueset = 'fatherComments.images_new[' + sonindex + '].direction';
    this.setData({
      [valueset]: dir
    })
  },
  //2. 获取子评论
  getComments: function(e) {
    var that = this;
    that.auth = that.selectComponent("#auth");
    if (that.data.auth && that.data.hasPhone) {
      var act = that.data.fatherComments
      if (act.type == "VIDEO") {
        that.setData({
          isPlay: false
        })
      }
      that.setData({
        comment: [],
        showUpload: false,
      })

      var last_content = null;
      var lastId = ""
      var lastTimestamp = 0
      var requestUrl = api.commentList + '?activityId=' + that.data.uuid + '&feelingId=' + that.data.commId
      if (that.data.comment && that.data.comment.length > 0) {
        last_content = that.data.comment[that.data.comment.length - 1]
        lastId = last_content.id
        lastTimestamp = last_content.createTime
        requestUrl = requestUrl + '&lastId=' + lastId + '&lastTimestamp=' + lastTimestamp
      }
      util.pututrequest(requestUrl, 'GET').then((res) => {
        if (res && res.code == 200) {
          this.setData({
            commentflag: true,
            hiddenAll:false
          })
          var tt = res.data.comments;
          if (tt && tt.length > 0) {
            for (let i = 0; i < tt.length; i++) {
              tt[i].to_now = date_util.getToNow(tt[i].createTime)
              if (tt[i].user) {
                if (tt[i].user.avatarUrl) {
                  tt[i].user.photo = tt[i].user.avatarUrl
                } else {
                  tt[i].user.photo = 'http://simul.dpaper.cn/miniprogram/images/index/photo.jpeg'
                }
              }
              this.setData({
                comment: tt,
              })
            }
          }
        }

      })
    } else {
      that.auth.showAuth()
    }
  },
  // 2.1 评论框焦点
  onFocus: function(e) {
    this.setData({
      phValue: " ",

    })
  },

  // 2.3 评论框输入
  commentInput: function(e) {
    this.setData({
      comment_content: e.detail.value
    })
  },
  // 2.4 发送子评论
  sendComment: function(e) {
    var that = this;
    var comm = e.currentTarget.dataset.comm
    var count = this.data.fatherComments.comment_count
    if (comm == '' || comm == null) {
      wx.showToast({
        title: '请输入评论内容!',
        icon: 'success',
        duration: 2000
      })
      return;
    }
    var commArry = []
    if (that.data.comment.length > 0) {
      commArry = that.data.comment
      commArry.unshift({
        "id": 1900,
        "to_now": '刚刚',
        "user": {
          "nickname": app.globalData.userInfo.nickname,
          "photo": that.data.userInfo.avatarUrl,
        },
        "content": comm
      })
    } else {
      commArry.push({
        "id": 1900,
        "to_now": '刚刚',
        "user": {
          "nickname": app.globalData.userInfo.nickname,
          "photo": that.data.userInfo.avatarUrl,
        },
        "content": comm
      })
    }

    this.setData({
      comment: commArry,
    })
    util.pututrequest(api.comment, 'POST', {
      feelingId: that.data.commId,
      content: comm,
      activityId: that.data.uuid
    }).then((res) => {
      if (res && res.code == 200) {
        var tt = 'fatherComments.comment_count'
        wx.showToast({
          title: '评论成功!',
          icon: 'success',
          duration: 2000
        })
        this.setData({
          phValue: "表达感受...",
          comment_content: '',
          [tt]: count + 1,
        })
      }
    })
  },
  click_blank: function(e) {
    this.setData({
      commentflag: false,
      simulflag: false,
      hiddenAll:true,
      hiddenShare: true,
      showUpload: true,
    })
  },

  // 播放音频
  audioPlay: function(e) {
    var that = this,
      fatherComments = that.data.fatherComments;
    var vidSrc = fatherComments.path;
    fatherComments.bl = true;
    that.setData({
      fatherComments: fatherComments
    })
    player.play(vidSrc, () => {
      //播放完成回调
    });
  },
  // 停止音频
  audioStop: function(e) {
    var that = this,
      fatherComments = that.data.fatherComments;
    //切换显示状态
    fatherComments.bl = false;
    that.setData({
      fatherComments: fatherComments
    })
    player.stop()
  },


  gotoUser: function(e) {
    player.stop()
    var that = this
    var faComm = that.data.fatherComments
    var user = faComm.user
    if (user) {
      var userStr = JSON.stringify(user);
      var user64 = base64.encode(userStr);
      var userEncode = encodeURIComponent(user64);

      wx.navigateTo({
        url: '/pages/user/user?userObj=' + userEncode,
        success: function() {},
        fail: function() {},
        complete: function() {}
      })

    } else {
      wx.showModal({
        title: '错误提示',
        content: '该用户在本产品中走丢了，我们正在找回他（她）',
        confirmText: "我知道了",
        showCancel: false,
      })
    }
  },

  gotoSimulUser: function(e) {
    player.stop()
    var that = this
    var item = e.currentTarget.dataset.item
    var user = item.user
    if (user) {
      var userStr = JSON.stringify(user);
      var user64 = base64.encode(userStr);
      var userEncode = encodeURIComponent(user64);

      wx.navigateTo({
        url: '/pages/user/user?userObj=' + userEncode,
        success: function() {},
        fail: function() {},
        complete: function() {}
      })

    } else {
      wx.showModal({
        title: '错误提示',
        content: '该用户在本产品中走丢了，我们正在找回他（她）',
        confirmText: "我知道了",
        showCancel: false,
      })
    }
  },

  showSimul: function(e) {
    var that = this
    wx.getSystemInfo({
      success: function(res) {
        let type = res.system
        if (type.indexOf("Android") != -1) {
          wx.showModal({
            title: '跳转至同感App',
            content: '亲爱的主人,很遗憾,同感app暂时未支持您的设备类型,您还是在小程序里尽情玩耍吧!'
          })
        }
        if (type.indexOf("iOS") != -1) {
          wx.showModal({
            title: '跳转至同感App',
            content: '亲爱的主人,请到AppStore里下载同感App查看更多同感动态!'
          })
        }
      }
    })

  },


  login: function() {
    return new Promise(function(resolve, reject) {
      wx.login({
        success: function(res) {
          if (res.code) {
            resolve(res);
          } else {
            reject(res);
          }
        },
        fail: function(err) {
          reject(err);
        }
      });
    });
  },

  actionHandle: function() {

  },
  gotoDetail: function() {
    var that = this
    wx.navigateTo({
      url: '/pages/detail/detail?uuid=' + that.data.uuid + '&source=index&commId=' + that.data.commId + '&type=1',
      success: function() {},
      fail: function() {},
      complete: function() {}
    })
  },
  gotoIndex: function() {
    var that = this
    wx.switchTab({
      url: '/pages/index/index'
    });
  },
  // 图片预览
  previewImage: function(e) {
    var that = this
    var current = e.target.dataset.src;
    var allImages = that.data.fatherComments.images_new
    const imgList = allImages.map(function(value, index, array) {
      return value.url_src
    })
    wx.previewImage({
      current: current, // 当前显示图片的http链接  
      urls: imgList // 需要预览的图片http链接列表  
    })
  },

})